//
//  HandlerManager.cpp
//  xyz
//
//  Created by jorsun on 14-3-14.
//
//

#include "HandlerManager.h"
static HandlerManager* m_pInstance;
HandlerManager::HandlerManager(){
    
}

HandlerManager::~HandlerManager(){
    
}
HandlerManager* HandlerManager::getInstance(){
    if (m_pInstance==NULL ){
        m_pInstance = new HandlerManager();
    }
    return m_pInstance;
}
void HandlerManager::init(){
    LoginHandler* loginHandler=new LoginHandler();
    m_pInstance->addHandler(loginHandler);
    BattleHandler* battleHandler=new BattleHandler();
    m_pInstance->addHandler(battleHandler);
}

/**
 * ×¢²áIMessageHandler
 *
 * @param handler
 * @throws IllegalStateException
 *             µ±ÖØ¸´×¢²áÍ¬Ò»ÏûÏ¢µÄÀàÐÍµÄ´¦ÀíÆ÷Ê±»áÅ×³ö´ËÒì³£
 * @throws IllegalArgumentException
 *             handlerÎª¿ÕÊ±
 *
 */
void HandlerManager::addHandler(BaseHandler* handler){
    if (handler == NULL) {
        CCLOG("handler is null");
        return;
    }
    if (handler->getTypes() == NULL) {
        CCLOGERROR("Message Handler has no  type, handler name=[%s]",typeid(handler).name());
        return;
    }
    for(int i=0;i<(sizeof(handler->getTypes())/sizeof(short));i++){
        short type=handler->getTypes()[i];
        BaseHandler* _handler=	handlers[type];
        if(_handler!=NULL){
            CCLOGERROR("Duplicate Message Handler for type [%d]",type);
        }
        handlers.insert(pair<short,BaseHandler*>(type,handler));
    }
}
void HandlerManager::execute(BaseMessage* message) {
    BaseHandler* handler=handlers[message->getType()];
    if(handler==NULL){
        CCLOGERROR("this Message is not registered [%d]",message->getType());
        return;
    }
    handler->execute(message);
}